<script setup lang="ts">
import { Lock, UserFilled } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
import { FormTextFieldValidator } from 'my-web-core/validators';
import { onMounted, reactive, ref } from 'vue';

import AuthService from '@/features/authentication/services/auth-service';
import UsersService from '@/features/users/services/users-service';
import { showWarning } from '@/shared/message/message-utils';

defineProps<{
  id?: string | null;
}>();

const emit = defineEmits<{
  (e: 'cancel'): void;
  (e: 'ok'): void;
}>();

const usernameInput = ref(null);
const ruleFormRef = ref<FormInstance>();

const ruleForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
});

const rules = reactive({
  username: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        const errorMessage = new FormTextFieldValidator({
          label: '用户名',
          value: value,
        }).validate();

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
  password: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        const errorMessage = new FormTextFieldValidator({
          label: '密码',
          value: value,
          label2: '确认密码',
          value2: ruleForm.confirmPassword,
        }).validate();

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
  confirmPassword: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        const errorMessage = new FormTextFieldValidator({
          label: '确认密码',
          value: value,
          label2: '密码',
          value2: ruleForm.password,
        }).validate();

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
});

onMounted(() => (usernameInput.value! as any).focus());

function onOk(form: FormInstance | undefined): void {
  form?.validate(async (valid) => {
    if (valid) {
      const usernameExists = await new AuthService().checkOnUsername(
        ruleForm.username,
      );

      if (!usernameExists) {
        await new UsersService().add({
          username: ruleForm.username,
          fullName: ruleForm.username,
          password: ruleForm.password,
        });

        emit('ok');

        // Resets form values.
        form?.resetFields();
      } else {
        showWarning('该用户名已被占用，请重新输入。');
      }
    }
  });
}

function onCancel(form: FormInstance | undefined): void {
  // Closes model.
  emit('cancel');

  // Resets validation status.
  form?.resetFields();
}
</script>

<template>
  <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules">
    <el-form-item prop="username">
      <el-input
        ref="usernameInput"
        v-model="ruleForm.username"
        :prefix-icon="UserFilled"
        placeholder="用户名"
      />
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="ruleForm.password"
        :prefix-icon="Lock"
        type="password"
        autocomplete="off"
        placeholder="密码"
      />
    </el-form-item>
    <el-form-item prop="confirmPassword">
      <el-input
        v-model="ruleForm.confirmPassword"
        :prefix-icon="Lock"
        type="password"
        autocomplete="off"
        placeholder="确认密码"
      />
    </el-form-item>
    <div class="button-container">
      <el-button @click="onCancel(ruleFormRef)">取消</el-button>
      <el-button type="primary" @click="onOk(ruleFormRef)">保存</el-button>
    </div>
  </el-form>
</template>

<style scoped>
.button-container {
  display: flex;
  flex-direction: row;
  justify-content: end;
}
</style>
